package com.jt.util;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 对象与JSON相互转换工具API
 * @author Administrator
 */
public class ObjectMapperUtil {
	private static final ObjectMapper MAPPER=new ObjectMapper();
	/**
	 * 将对象转换成JSON
	 */
	public static String toJSON(Object object) {
		String json=null;
		try {
			json=MAPPER.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return json;
	}
	
	/**
	 * 将JSON转换成对象
	 */
	public static <T>T toObject(String json,Class<T> targetClass) {
		T object=null;
		try {
			object=MAPPER.readValue(json, targetClass);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return object;
	}
}
